package com.wman.drawing.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Xfermode;
import android.util.AttributeSet;
import android.view.View;

import com.wman.drawing.R;
import com.wman.sheep.common.utils.DensityUtil;

import androidx.annotation.Nullable;

/**
 * @ProjectName: wman
 * @Package: com.wman.drawing.view
 * @ClassName: AvatarView
 * @Description: java类作用描述
 * @Author: wman
 * @CreateDate: 2019/11/5 17:13
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/11/5 17:13
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class AvatarView extends View {
    private static final int WIDTH = DensityUtil.dip2px(300);
    private static final int PADDING = DensityUtil.dip2px(50);
    private static final int EDGE_WIDTH = DensityUtil.dip2px(10);
    private Bitmap mBitmap;
    private Xfermode mXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private RectF mSaveArea = new RectF();

    public AvatarView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    {
        mBitmap = getAvatar(WIDTH);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mSaveArea.set(PADDING, PADDING, PADDING + WIDTH, PADDING + WIDTH);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawOval(PADDING, PADDING, PADDING + WIDTH, PADDING + WIDTH, mPaint);
        /**
         * 离屏缓冲
         */
        int saved = canvas.saveLayer(mSaveArea, mPaint);
        canvas.drawOval(PADDING + EDGE_WIDTH, PADDING + EDGE_WIDTH,
                PADDING + WIDTH - EDGE_WIDTH, PADDING + WIDTH - EDGE_WIDTH, mPaint);
        mPaint.setXfermode(mXfermode);
        canvas.drawBitmap(mBitmap, PADDING, PADDING, mPaint);
        mPaint.setXfermode(null);
        canvas.restoreToCount(saved);
    }

    private Bitmap getAvatar(int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(), R.mipmap.icon_avatar, options);
        options.inJustDecodeBounds = false;
        options.inDensity = options.outWidth;
        options.inTargetDensity = width;
        return BitmapFactory.decodeResource(getResources(), R.mipmap.icon_avatar, options);
    }
}
